package cn.zh.npro.Adapter;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.squareup.picasso.Picasso;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import cn.zh.npro.Item.RpItem;
import cn.zh.npro.MyApplication;
import cn.zh.npro.R;
import cn.zh.npro.Util.BaseUrl;
import cn.zh.npro.Util.DensityUtil;
import cn.zh.npro.Util.JSONUtils;
import cn.zh.npro.Util.Tp;
import cn.zh.npro.bean.GoodsSpec;
import cn.zh.npro.bean.TradeGoods;
import cn.zh.npro.bean.Unites;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by WYN on 2018/3/15 0015.
 */

public class RpAdapter extends BaseAdapter {
    Context context;
    ArrayList<RpItem> arrayList;
    ArrayList<GoodsSpec.ResBean> mArrayList;
    LayoutInflater inflater;
    TextView text;
    int type = 0;
    Dialog dialog;
    //整体布局View，确定pop显示位置
    View tview, popview;
    boolean istrue = false;
    String customerID;

    public RpAdapter(Context context, ArrayList<RpItem> arrayList, TextView text, int type, View tview, View popview, String customerID) {
        this.context = context;
        this.arrayList = arrayList;
        this.text = text;
        this.type = type;
        this.tview = tview;
        this.popview = popview;
        this.customerID = customerID;


    }

    @Override
    public int getCount() {
        return arrayList.size();
    }

    @Override
    public Object getItem(int i) {
        return arrayList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        Holder holder = null;
        if (null == view) {
            holder = new Holder();
            view = LayoutInflater.from(context).inflate(R.layout.rp_layout, null, false);
            holder.gimga = view.findViewById(R.id.gimga);
            holder.gname = view.findViewById(R.id.gname);
            holder.guint = view.findViewById(R.id.guint);
            holder.gprice = view.findViewById(R.id.gprice);
            holder.sptxt = view.findViewById(R.id.sptxt);
            holder.reduce = view.findViewById(R.id.reduce);
            holder.cadd = view.findViewById(R.id.cadd);
            holder.contxt = view.findViewById(R.id.contxt);
            view.setTag(holder);
        } else {
            holder = (Holder) view.getTag();
        }
        if (arrayList.get(i).getIndexURL().equals("")) {
            Picasso.with(MyApplication.getsInstance()).load(R.mipmap.noimage).into(holder.gimga);
        } else {
            Picasso.with(MyApplication.getsInstance()).load(arrayList.get(i).getIndexURL()).into(holder.gimga);
        }
        holder.gname.setText(arrayList.get(i).getGoodsName());
        holder.guint.setText("单位" + arrayList.get(i).getUnit2());
//        holder.gprice.setText("¥" + arrayList.get(i).getSellPrice()+"元/卷");
        DecimalFormat format = new DecimalFormat("0.00");
        String p = format.format(new BigDecimal(arrayList.get(i).getSellPrice()));
        holder.gprice.setText("¥" + p+"元/卷");

        holder.sptxt.setText(arrayList.get(i).getTradeSpec());
        holder.contxt.setText(arrayList.get(i).getNum() + "");
        holder.contxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //点击弹窗
                //getDialognum(i);
                popview.setVisibility(View.VISIBLE);
                String GoodsId = arrayList.get(i).getGoodsId();
//                holder.contxt.post(new Runnable() {
//                    @Override
//                    public void run() {
//
//                    }
//                })
                getmessage(GoodsId, i);
//
            }
        });
        final Holder finalHolder = holder;
        holder.reduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (type == 0) {
                    if (arrayList.get(i).getNum() > 0) {
                        int a = arrayList.get(i).getNum() - 1;
                        arrayList.get(i).setNum(a);
                        finalHolder.contxt.setText(a + "");
                        int ta = 0, tb = 0;
                        for (int j = 0; j < arrayList.size(); j++) {
                            if (arrayList.get(j).getNum() != 0) {
                                ta = ta + 1;
                                tb = tb + arrayList.get(j).getNum();
                            }
                        }
                        text.setText("共计" + ta + "种商品" + tb + "件");
                    }
                } else {

                    if (arrayList.get(i).getNum() > 1) {
                        int a = arrayList.get(i).getNum() - 1;
                        arrayList.get(i).setNum(a);
                        finalHolder.contxt.setText(a + "");
                        int ta = 0, tb = 0;
                        for (int j = 0; j < arrayList.size(); j++) {
                            if (arrayList.get(j).getNum() != 0) {
                                ta = ta + 1;
                                tb = tb + arrayList.get(j).getNum();
                            }
                        }
                        text.setText("共计" + ta + "种商品" + tb + "件");
                    } else {
                        if (type == 1) {
                            getDialog(i);
                        }
                    }
                }
            }
        });

        holder.cadd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int b = arrayList.get(i).getNum() + 1;
                arrayList.get(i).setNum(b);
                finalHolder.contxt.setText(b + "");
                int ta = 0, tb = 0;
                for (int j = 0; j < arrayList.size(); j++) {
                    if (arrayList.get(j).getNum() != 0) {
                        ta = ta + 1;
                        tb = tb + arrayList.get(j).getNum();
                    }
                }
                text.setText("共计" + ta + "种商品" + tb + "件");

            }
        });

        if (type == 1) {
            int ta = 0, tb = 0;
            for (int j = 0; j < arrayList.size(); j++) {
                if (arrayList.get(j).getNum() != 0) {
                    ta = ta + 1;
                    tb = tb + arrayList.get(j).getNum();
                }
            }
            text.setText("共计" + ta + "种商品" + tb + "件");
        }

        return view;
    }


    public class Holder {
        ImageView gimga, reduce, cadd;
        TextView gname, guint, gprice, contxt,sptxt;
    }


    public void getmessage(final String GoodsId, final int postion) {

        OkHttpUtils.get(BaseUrl.GetGoodsUnit)
                .params("goodsId", GoodsId)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        Log.e("777", "xx" + s);
                        Unites unites = JSONUtils.parseJSON(s, Unites.class);

                        if (unites.getRes() != null && unites.getRes().size() > 0) {
                            String countRate = unites.getRes().get(0).getUnit();
                            getmessage2(tview, postion, countRate, unites, GoodsId);
//
                        } else {
                            Toast.makeText(MyApplication.getsInstance(), "没有此单位！", Toast.LENGTH_SHORT).show();
                        }

                    }
                });


    }

    public void getmessage2(final View view, final int pos, final String St, final Unites unites, final String GoodsId) {

        OkHttpUtils.get(BaseUrl.GetGoodsSpec)
                .params("goodsId", GoodsId)
                .params("customerID", customerID)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        Log.e("yst", "xx" + s);
                        final GoodsSpec goodsSpec = JSONUtils.parseJSON(s, GoodsSpec.class);

                        if (goodsSpec.getRes() != null && goodsSpec.getRes().size() > 0) {
                            String SpecName = goodsSpec.getRes().get(0).getSpecName();
//                            String Unit = goodsSpec.getRes().get(0).getUnit();
                              String SpecID = goodsSpec.getRes().get(0).getSpecID();

//                            final Double Rate = goodsSpec.getRes().get(0).getRate();
                            getpop(view, pos, St, unites, SpecName, goodsSpec,SpecID,Stock);
                        } else {
                            Toast.makeText(MyApplication.getsInstance(), "没有此规格！", Toast.LENGTH_SHORT).show();


                        }

                    }
                });


    }

    public void getDialog(final int position) {
        View v = inflater.inflate(R.layout.delete, null);// 得到加载view
        LinearLayout layout = (LinearLayout) v
                .findViewById(R.id.delete);// 加载布局

        dialog = new Dialog(MyApplication.getsInstance(), R.style.MyDialogStyle);
        dialog.show();
        dialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.MATCH_PARENT));
        v.findViewById(R.id.ocancle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        v.findViewById(R.id.osure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                //s删除地址网络请求
                arrayList.remove(position);
                notifyDataSetChanged();
            }
        });
    }

    List<String> ccList = new ArrayList<String>();
    List<String> ccList2 = new ArrayList<String>();
    String  Unit2="米";
    String Length;
    String Width;
    String Height;
    String  selectedSpec;
    String ZONGJIA;
    String specID;


    double Rate2 ;
    double Count2;
    double Stock;
    double specname1;
    double specname2;



    //弹窗
    public void getpop(View view, final int pos, final String St, final Unites unites, String SpecName, final GoodsSpec goodsSpec,String SpecID,double Stock) {

        View vp = LayoutInflater.from(context).inflate(R.layout.sizepop, null, false);
        View spview = vp.findViewById(R.id.spview);
//        LinearLayout gsize = vp.findViewById(R.id.gsize);
        final LinearLayout teview = vp.findViewById(R.id.teview);
        ccList.clear();
        ccList2.clear();

        List<Unites.ResBean> res = unites.getRes();
        for (int i = 0; i < res.size(); i++) {
            String unit = res.get(i).getUnit();
            ccList.add(unit);

        }
        List<GoodsSpec.ResBean> res2 = goodsSpec.getRes();
        for (int i = 0; i < res2.size(); i++) {
           selectedSpec = res2.get(i).getSpecName();
            specID = res2.get(i).getSpecID();
            specname1 = res2.get(i).getSpecName1();
            specname2 = res2.get(i).getSpecName2();
//            Stock = res2.get(i).getStock();
//            ccList2.add(selectedSpec + ("(----库存：" + Stock));
            ccList2.add(selectedSpec);



        }

//        final ImageView gsimage = vp.findViewById(R.id.gsimage);
        final ImageView gsima = vp.findViewById(R.id.gsima);
        ImageView pdete = vp.findViewById(R.id.pdete);
        final TextView pgprice = vp.findViewById(R.id.pgprice);
        final TextView gunit = vp.findViewById(R.id.gunit);
        final Spinner spinnerdanwei = vp.findViewById(R.id.spinnerdanwei);
        //ArrayAdapter adapter = new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item, ccList);
        final Spinner spinnerguige = vp.findViewById(R.id.spinnerguige);
        spinnerdanwei.setAdapter(new SpinnerAdapter(ccList,context));

        final EditText etnum = vp.findViewById(R.id.etnum);
        final EditText etpri = vp.findViewById(R.id.etpri);
        final TextView ttal = vp.findViewById(R.id.ttal);
        spinnerdanwei.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Unit2= ccList.get(position).toString();

//                int indexOf = selectedSpec.indexOf("*");
//                int indexOf2 = selectedSpec.lastIndexOf("*");
//                Length = "" + selectedSpec.substring(0, indexOf);
//                Width = "" + selectedSpec.substring(indexOf + 1, indexOf2);
//                double Lengthdouble = Double.valueOf(Length);
//                double Widthdouble = Double.valueOf(Width);
                String s1 =etnum.getText().toString();
                String s2 =etpri.getText().toString();
//                Double s3 = Double.parseDouble(s1);


                if(Unit2.equals("米")){
                    ZONGJIA=String.valueOf(Tp.gettotalprice(selectedSpec,s2,s1,"1"));
                    Rate2 = specname1;
                    Count2 = specname1;


                } if(Unit2.equals("平方米"))
                {
                    ZONGJIA=String.valueOf(Tp.gettotalprice(selectedSpec,s2,s1,"2"));

                    Rate2 = specname1*specname2;
                    Count2 = specname1 * specname2;
                }
                else {
                    ZONGJIA=String.valueOf(Tp.gettotalprice(selectedSpec,s2,s1,"3"));
                }
                DecimalFormat format = new DecimalFormat("0.00");
                String p = format.format(new BigDecimal(ZONGJIA));

                ttal.setText(p);
                pgprice.setText("¥" + p);

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }});


//        ArrayAdapter adapter2 = new ArrayAdapter<String>(context,R.layout.item_rp_,ccList2);
        spinnerguige.setAdapter(new SpinnerAdapter(ccList2,context));
        spinnerguige.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                selectedSpec= ccList2.get(position).toString();
                specID = goodsSpec.getRes().get(position).getSpecID();
                specname1 = goodsSpec.getRes().get(position).getSpecName1();
                specname2 = goodsSpec.getRes().get(position).getSpecName2();
//                int indexOf = selectedSpec.indexOf("*");
//                int indexOf2 = selectedSpec.lastIndexOf("*");
//                Length = "" + selectedSpec.substring(0, indexOf);
//                Width = "" + selectedSpec.substring(indexOf + 1, indexOf2);
//                double Lengthdouble = Double.valueOf(Length);
//                double Widthdouble = Double.valueOf(Width);
                String s1 =etnum.getText().toString();
                String s2 =etpri.getText().toString();





                if(Unit2.equals("米")){
                    ZONGJIA=String.valueOf(Tp.gettotalprice(selectedSpec,s2,s1,"1"));

                    Rate2 = specname1;
                    Count2 = specname1;

                } if(Unit2.equals("平方米"))
                {
                    ZONGJIA=String.valueOf(Tp.gettotalprice(selectedSpec,s2,s1,"2"));

                    Rate2 = specname1*specname2;
                    Count2 = specname1*specname2;
                }
                else {
                    ZONGJIA=String.valueOf(Tp.gettotalprice(selectedSpec,s2,s1,"3"));
                }
                DecimalFormat format = new DecimalFormat("0.00");
                String p = format.format(new BigDecimal(ZONGJIA));

                ttal.setText(p);
                pgprice.setText("¥" + p);

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }});

        if (arrayList.get(pos).getIndexURL().equals("")) {
            Picasso.with(MyApplication.getsInstance()).load(R.mipmap.noimage).into(gsima);
        } else {
            Picasso.with(MyApplication.getsInstance()).load(arrayList.get(pos).getIndexURL()).into(gsima);
        }
        pgprice.setText("¥" + arrayList.get(pos).getPrice_Detail());
//        gsimage.setBackgroundResource(R.mipmap.arrowon);
        gunit.setText(arrayList.get(pos).getUnit());

        etnum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String en = editable.toString();
                String ep = etpri.getText().toString();

//                int indexOf = selectedSpec.indexOf("*");
//                int indexOf2 = selectedSpec.lastIndexOf("*");
//                Length = "" + selectedSpec.substring(0, indexOf);
//                Width = "" + selectedSpec.substring(indexOf + 1, indexOf2);
//                double Lengthdouble = Double.valueOf(Length);
//                double Widthdouble = Double.valueOf(Width);



                if (Unit2.equals("米")) {
                    ZONGJIA = String.valueOf(Tp.gettotalprice(selectedSpec, ep, en, "1"));
                    Rate2 = specname1;
                    Count2 = specname1;

                }
                if (Unit2.equals("平方米")) {
                    ZONGJIA = String.valueOf(Tp.gettotalprice(selectedSpec, ep, en, "2"));
                    Rate2 = specname1 * specname2;
                    Count2 = specname1 * specname2;
                }


                else{

                    ZONGJIA=String.valueOf(Tp.gettotalprice(selectedSpec,ep,en,"3"));
                }
                DecimalFormat format = new DecimalFormat("0.00");
                String p = format.format(new BigDecimal(ZONGJIA));

                ttal.setText(p);
                pgprice.setText("¥" + p);


            }
        });
        etpri.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String en = editable.toString();
                String ep = etnum.getText().toString();
//                int indexOf = selectedSpec.indexOf("*");
//                int indexOf2 = selectedSpec.lastIndexOf("*");
//                Length = "" + selectedSpec.substring(0, indexOf);
//                Width = "" + selectedSpec.substring(indexOf + 1, indexOf2);
//                double Lengthdouble = Double.valueOf(Length);
//                double Widthdouble = Double.valueOf(Width);



                if (Unit2.equals("米")) {
                    ZONGJIA = String.valueOf(Tp.gettotalprice(selectedSpec, ep, en, "1"));

                    Rate2 = specname1;
                    Count2 = specname1;
                }
                if (Unit2.equals("平方米")) {
                    ZONGJIA = String.valueOf(Tp.gettotalprice(selectedSpec, ep, en, "2"));
                    Rate2 = specname1 * specname2;
                    Count2 = specname1 * specname2;
                }


                else{
                    ZONGJIA=String.valueOf(Tp.gettotalprice(selectedSpec,ep,en,"3"));
                }



//                int enu = Integer.valueOf(en).intValue();
//                double epr = Double.valueOf(ep).doubleValue();
                DecimalFormat format = new DecimalFormat("0.00");
                String p = format.format(new BigDecimal(ZONGJIA));

                ttal.setText(p);
                pgprice.setText("¥" + p);

            }
        });
        etpri.setText(etpri.getText());
        etnum.setText(etnum.getText());
        

        final PopupWindow popupWindow = new PopupWindow(vp, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        setBackgroundAlpha(0.5f);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
        popupWindow.setAnimationStyle(R.style.popwin_pop_style);

        popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

                setBackgroundAlpha(1.0f);

            }
        });
        spview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
        pdete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                
                popupWindow.dismiss();
            }
        });
//        gsize.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                //商品型号弹窗
//                performAnim(teview);
//                if (istrue) {
//                    gsimage.setBackgroundResource(R.mipmap.arrowdown);
//                } else {
//                    gsimage.setBackgroundResource(R.mipmap.arrowon);
//                }
//            }
//        });

        vp.findViewById(R.id.osure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String en = etnum.getText().toString();
                String ep = etpri.getText().toString();
                if (en.equals("") || ep.equals("")) {
                    popupWindow.dismiss();
                    return;
                }
                int enu = Integer.valueOf(en).intValue();
                double enp = Double.valueOf(ep).doubleValue();
                double rate2 = Double.valueOf(Rate2).doubleValue();
                double count2 = Double.valueOf(Count2).doubleValue();
                double sellprice = Double.valueOf(enp*Rate2).doubleValue();
//                DecimalFormat format = new DecimalFormat("0.00");
//                String s = format.format(new BigDecimal(sellprice));



                arrayList.get(pos).setNum(enu);
                arrayList.get(pos).setPrice_Detail(ZONGJIA);
                arrayList.get(pos).setTradeSpec(selectedSpec);
                arrayList.get(pos).setPrice2(enp);
                arrayList.get(pos).setRate2(rate2);
                arrayList.get(pos).setSellPrice(sellprice);
                arrayList.get(pos).setCount2(count2);
                arrayList.get(pos).setUnit2(Unit2);
                arrayList.get(pos).setSpecID(specID);





                popupWindow.dismiss();
                notifyDataSetChanged();
            }
        });
    }

    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = ((Activity) context).getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        ((Activity) context).getWindow().setAttributes(lp);

    }


    private void performAnim(final View view) {
        //View是否显示的标志
        istrue = !istrue;
        //属性动画对象
        final ValueAnimator va;
        final int heigh = DensityUtil.dp2px(MyApplication.getsInstance(), 100);
        if (istrue) {
            //显示view，高度从0变到height值
            va = ValueAnimator.ofInt(0, heigh);
        } else {
            //隐藏view，高度从height变为0
            va = ValueAnimator.ofInt(heigh, 0);
        }
        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                //获取当前的height值
                int h = (Integer) valueAnimator.getAnimatedValue();
                //动态更新view的高度
                view.getLayoutParams().height = h;
                view.requestLayout();
            }
        });
        va.setDuration(500);
        //开始动画
        va.start();
    }


}
